package page

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/blog/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/blog/rpc/blogclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPageByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPageByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPageByIdLogic {
	return &GetPageByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPageByIdLogic) GetPageById(req *types.IDReq) (*types.CMSPageInfoResp, error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.BlogRpc.BackendGetPageById(l.ctx, &blogclient.PageIdReq{
		Id:           req.Id,
		WithMeta:     pointy.GetPointer(uint32(1)),
		WithMedia:    pointy.GetPointer(uint32(1)),
		WithCategory: pointy.GetPointer(uint32(1)),
		WithTag:      pointy.GetPointer(uint32(1)),
		WithContent:  pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var meta []*types.MetaInfo
	var photoCount *uint32
	var viewCount *uint32
	var forwardCount *uint32
	var pendingStatus *uint32
	if len(data.Meta) > 0 {
		for _, v := range data.Meta {
			if v.Key != nil && v.Value != nil {
				switch *v.Key {
				case "photoCount":
					if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil {
						photoCount = pointy.GetPointer(uint32(i))
					}
				case "viewCount":
					if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil {
						viewCount = pointy.GetPointer(uint32(i))
					}
				case "forwardCount":
					if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil {
						forwardCount = pointy.GetPointer(uint32(i))
					}
				case "pendingStatus":
					if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil {
						pendingStatus = pointy.GetPointer(uint32(i))
					}
				default:
					meta = append(meta, &types.MetaInfo{
						Id:    v.Id,
						Key:   v.Key,
						Value: v.Value,
					})
				}
			}
		}
	}

	var media []*types.MediaInfo
	if len(data.Media) > 0 {
		for _, v := range data.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			filename, mimeType, metaData := utils.ParseMetaData(v.MetaData)
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       pointy.GetPointer(url),
				Name:      pointy.GetPointer(filename),
				MimeType:  pointy.GetPointer(mimeType),
				AltText:   v.AltText,
				MetaData:  pointy.GetPointer(metaData),
			})
		}
	}

	var categories []*types.CMSTermInfo
	if len(data.Categories) > 0 {
		for _, v := range data.Categories {
			categories = append(categories, &types.CMSTermInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				Name: v.Name,
				Slug: v.Slug,
			})
		}
	}

	var tags []*types.CMSTermInfo
	if len(data.Tags) > 0 {
		for _, v := range data.Tags {
			tags = append(tags, &types.CMSTermInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				Name: v.Name,
				Slug: v.Slug,
			})
		}
	}

	option := util.GetAuditOptionByStatus(data.Status)
	var uri *string
	if data.Uri != nil && len(*data.Uri) > 0 {
		if strings.HasPrefix(*data.Uri, l.svcCtx.Config.NfsConf.SiteUrl) {
			uri = data.Uri
		} else {
			uri = pointy.GetPointer(l.svcCtx.Config.NfsConf.SiteUrl + *data.Uri)
		}
	}

	return &types.CMSPageInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.CMSPageInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Title:         data.Title,
			Slug:          data.Slug,
			Content:       data.ContentFiltered,
			ContentHtml:   data.Content,
			Excerpt:       data.Excerpt,
			ParentId:      data.ParentId,
			AuthorId:      data.AuthorId,
			Status:        data.Status,
			PendingStatus: pendingStatus,
			CommentStatus: data.CommentStatus,
			Sort:          data.Sort,
			Visibility:    data.Visibility,
			Password:      data.Password,
			Uri:           uri,
			PhotoCount:    photoCount,
			ViewCount:     viewCount,
			ForwardCount:  forwardCount,
			CommentCount:  data.CommentCount,
			CanSubmit:     option.CanSubmit,
			Loaded:        pointy.GetPointer(modelx.FormatTime(time.Now(), "")),

			Meta:       meta,
			Media:      media,
			Categories: categories,
			Tags:       tags,
		},
	}, nil
}
